<template>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="商品名称" prop="GoodsName">
        <el-input v-model="ruleForm.GoodsName" />
      </el-form-item>

      <el-form-item label="商品分类" prop="GoodsTyoeId">
        <el-tree-select
    v-model="ruleForm.GoodsTyoeId"
    :data="getgoodsType"
    check-strictly
    :render-after-expand="false"
    style="width: 240px"
  />



      </el-form-item>

      <el-form-item label="商品标签" prop="GoodskabelId">

        <el-select-v2
        v-model="ruleForm.GoodskabelId"
        placeholder="请选择"
        :options="getgoodsLaber"
      />

      </el-form-item>

      <el-form-item label="商品单价" prop="Price">
        <el-input v-model="ruleForm.Price" />
      </el-form-item>

      <el-form-item label="商品库存" prop="Number">
        <el-input v-model="ruleForm.Number" />
      </el-form-item>

      <el-form-item label="商品图片" prop="GoodsImages">
     
        <el-upload
    class="avatar-uploader"
    :action="`${apiUrl}/api/Imgse/Imgse`"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="ruleForm.GoodsImages" :src="getImageUrl(ruleForm.GoodsImages)" class="avatar"/>

    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
      </el-form-item>

      <el-form-item label="商品详细" prop="GoodsDesc">
       
        
        <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 350px; overflow-y: hidden;"
        v-model="ruleForm.GoodsDesc"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>

      </el-form-item>

      
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
  import axios from 'axios'
  import { useRouter,useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import type { UploadProps } from 'element-plus'

  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import { onBeforeUnmount,shallowRef, onMounted } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  const apiUrl = import.meta.env.VITE_APP_API_URL;
function getImageUrl(path) {
  if (!path) return '';
  if (path.startsWith('http')) return path;
  if (path.startsWith('/img/')) return apiUrl + path;
  if (path.startsWith('img/')) return apiUrl + '/' + path;
  return apiUrl + '/img/' + path.replace(/^\\/, '');
}
console.log(import.meta.env);
console.log(apiUrl);

  const router=useRouter();
  const route=useRoute();
  
  interface RuleForm {
    GoodsId:number
    GoodsName: string
    GoodsTyoeId: number
    GoodskabelId: number
    Price: number
    Number: number
    GoodsImages: string
    GoodsDesc: string
  }
  
  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive<RuleForm>({
    GoodsId:0,
    GoodsName: '',
    GoodsTyoeId:0,
    GoodskabelId:0,
    Price:0,
    Number:0,
    GoodsImages:'',
    GoodsDesc: '',
  })
  

  
  const rules = reactive<FormRules<RuleForm>>({
    GoodsName: [
      { required: true, message: '商品名必填', trigger: 'blur' },
      //{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    GoodsTyoeId: [
      {
        required: true,
        message: '分类必填',
        trigger: 'blur',
      },
    ],
    GoodskabelId: [
      {
        required: true,
        message: '标签必填',
        trigger: 'blur',
      },
    ],
    Price: [
      {
     
        required: true,
        message: '单价必填',
        trigger: 'blur',
      },
    ],
    Number: [
      {
        
        required: true,
        message: '库存必填',
        trigger: 'blur',
      },
    ],
    GoodsImages: [
      {
        required: true,
        message: '图片必填',
        trigger: 'blur',
      },
    ],
    GoodsDesc: [
      {
      
        required: true,
        message: '商品详情',
        trigger: 'blur',
      },
    ],
    
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('submit!',ruleForm)
        axios({
            url:'/api/Goods/UpdateGoods',
            method:'put',
            data:ruleForm
        }).then(res=>{
            console.log(res);
            if(res.data.code==200){
                ElMessage({
                message: '修改成功',
                type: 'success',
                })
                router.push('/GoodsList');
            
            }else{
                ElMessage.error(''+res.data.msg+'')
            }
            
        }).catch(err=>{
            console.log(err);
            
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))

  const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log("response=",response);
  
  //取到图片值
  ruleForm.GoodsImages=response.data
  
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg'&& rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是 JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}



 // 编辑器实例，必须用 shallowRef
 const editorRef = shallowRef()



let getgoodsType:any=ref([])
let getgoodsLaber:any=ref([])


//商品分类
const Typetree=()=>{
  axios({
    url:'/api/Goods/GetGoodsTypeListForTreeAsync',
    method:'post',
    data:{}
  }).then(res=>{
    console.log(res);
    
    
    getgoodsType.value=res.data.data
    getgoodsType.value.push({value:0,label:"全部"})
    
  })

}


//商品标签
const Laberlist=()=>{
  axios({
    url:'/api/Goods/GetGoodsLabelListForSelectasync',
    method:'get',
    params:{}
  }).then(res=>{
    console.log(res);
    if(res.data.code==200){
      getgoodsLaber.value=res.data.data;
      getgoodsLaber.value.push({value:0,label:"全部"})

    }
    
    
    
  })

}

//反填
const fantian=()=>{
  axios({
    url:'/api/Goods/Fantian',
    method:'get',
    params:{
      Id:route.query.Id
    }
  }).then(res=>{
    console.log(res);
    if(res.data.code==200){
      Object.assign(ruleForm,res.data.data)
    }

    
  }).catch(err=>{
    console.log(err);
    
  })


}

// 模拟 ajax 异步获取内容
onMounted(() => {
  Laberlist()
  Typetree()
  fantian()
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
  </script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

 
  